package org.example.controller;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.example.pojo.Result;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.utils.JwtUtil;
import org.example.utils.Md5Util;
import org.example.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$")String username, @Pattern(regexp = "^\\S{5,16}$")String password){
        //判断用户名是否存在
        User u =userService.findByUsername(username);
//        System.out.println("controller:"+username+" "+password);
        if(u == null){
            //不存在
            //注册
            userService.register(username,password);
            return Result.success();
        }else{
            //存在
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$")String username, @Pattern(regexp = "^\\S{5,16}$")String password){
        // 1. 构建缓存Key
        String userKey = "login:user:" + username;

        // 2. 先查询缓存（包括空值缓存）
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String cached = ops.get(userKey);

        // 3. 处理缓存命中情况
        if (cached != null) {
            // 如果是空值标记（表示用户不存在）
            if ("NULL".equals(cached)) {
                return Result.error("用户不存在1");
            }
        }

        //查找用户
        User u = userService.findByUsername(username);
        //判断用户是否存在
        if(u == null){
            ops.set(userKey, "NULL", 5 + (int)(Math.random() * 5), TimeUnit.MINUTES);
            return Result.error("用户不存在2");
        }
        //判断密码是否正确
        if(Md5Util.getMD5String(password).equals(u.getPassword())){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",u.getId());
            claims.put("username",u.getUsername());
            String token = JwtUtil.genToken(claims);
            ops = stringRedisTemplate.opsForValue();
            ops.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        //密码错误
        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(@RequestHeader(name = "Authorization") String token){
        //解析token
//        Map<String, Object> map = JwtUtil.parseToken(token);
        //获取username
//        String username = (String) map.get("username");
        Map<String,Object> map = ThreadLocalUtil.get();

        String username = (String) map.get("username");

        //根据用户名查询
        User user = userService.findByUsername(username);
        //返回值
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();

    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String picUrl){
        userService.updateAvatar(picUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        //1.校验密码
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        //判断以上参数是否为空
        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("以上参数不得为空");
        }

        //判断原密码是否正确
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUsername(username);
        if(!user.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("旧密码不相符");
        }

        //判断两次输入的新密码是否一致
        if(!newPwd.equals(rePwd)){
            return Result.error("两次新密码不一致");
        }

        //2.修改密码
        userService.updatePwd(newPwd);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);
        return Result.success();
    }

}
